package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.MediaEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author 王苑
 * @since 2022-07-29
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    @Autowired
    private IWmNewsService wmNewsService;

    @Autowired
    private IAuditService auditService;

    /**
     * 分页查询当前自媒体文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult queryByPage(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == null){
            return ResponseResult.errorResult(401,"请登录后操作！");
        }
        //1.构建分页对象
        IPage<WmNews> page = new Page<>();
        //2.构建查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //2.1必须条件 自媒体用户ID  排序 发布时间
        queryWrapper.eq(WmNews::getUserId,user.getUserId());
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        //2.2设置状态条件
        if (ObjectUtils.isNotEmpty(dto.getStatus())){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //2.3 设置频道条件
        if (ObjectUtils.isNotEmpty(dto.getChannelId())){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //2.4 设置关键字条件
        if (StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //2.5 设置时间区间条件
        if (ObjectUtils.isNotEmpty(dto.getBeginPubDate()) && ObjectUtils.isNotEmpty(dto.getEndPubDate())){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //3.执行查询
        this.page(page,queryWrapper);
        //4.返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),page.getRecords());
    }

    /**
     * 自媒体文章发布：保存自媒体文章；保存文章跟素材关系
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //0.获取登录自媒体用户
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == null) {
            return ResponseResult.errorResult(401, "请登录后操作！");
        }
        //1.创建自媒体文章对象,属性赋值
        WmNews wmNews = new WmNews();
        //1.1 将前端提交dto同名同类型属性直接拷贝
        BeanUtils.copyProperties(dto, wmNews);
        //1.2 手动给其他属性赋值
        wmNews.setUserId(user.getUserId());
        wmNews.setSubmitedTime(new Date());
        if (ObjectUtils.isEmpty(wmNews.getPublishTime())){
            wmNews.setPublishTime(new Date());
        }
        //1.3 设置封面属性 type-0-无图  type-1-单图  type-3-多图  type-(-1)-自动
        setWmnewImages(wmNews, dto);

        //2.执行保存
        this.save(wmNews);

        //3.保存自媒体文章跟素材引用关系
        //3.1 获取文章封面中素材
        List<ImageDto> coverImages = dto.getImages();
        //3.2 获取文章正文中素材
        List<ImageDto> contentImages = getIamgeFromContent(wmNews.getContent());

        //3.3 执行保存
        saveArticleMaterialRelation(coverImages, MediaEnum.MATERIAL_TYPE_REF_TYPE_CONVERIMG.getVal(), wmNews.getId());
        saveArticleMaterialRelation(contentImages, MediaEnum.MATERIAL_TYPE_REF_TYPE_CONTENTIMG.getVal(), wmNews.getId());

        //TODO 4.进入自媒体文章-自动审核逻辑
        log.info("执行保存自媒体文章，线程信息{}", Thread.currentThread().getName());
        auditService.audit(wmNews);

        return ResponseResult.okResult();
    }

    /**
     * 处理文章封面，封面类型
     *
     * @param wmNews
     * @param dto
     */
    private void setWmnewImages(WmNews wmNews, WmNewsDto dto) {
        //1.得到前端提交封面类型
        Integer type = wmNews.getType();
        List<ImageDto> images = dto.getImages();
        String imagesStr = "";
        switch (type) {
            case 0:
                //用户选择无图
                wmNews.setType(0);
                wmNews.setImages(null);
                break;
            case 1:
                //用户选择单图
                wmNews.setType(1);
                ImageDto imageDto = images.get(0);
                wmNews.setImages(imageDto.getUrl());
                break;
            case 3:
                //用户选择多图
                wmNews.setType(3);
                imagesStr = images.stream().map(ImageDto::getUrl).collect(Collectors.joining(","));
                wmNews.setImages(imagesStr);
                break;
            case -1:
                //用户选择自动,从正文中获取图片，当图片数量大于1小于3 设置为单图 、当图片大于等于3设置多图、当没有图片设置为无图
                List<ImageDto> list = getIamgeFromContent(dto.getContent());
                int size = list.size();
                if (size > 0 && size < 3) {
                    //单图 截取第一张图片作为封面
                    wmNews.setType(1);
                    ImageDto imageDto1 = list.get(0);
                    wmNews.setImages(imageDto1.getUrl());
                } else if (size >= 3) {
                    //多图 截图前三张图片
                    List<ImageDto> imageDtoList = list.subList(0, 3);
                    imagesStr = imageDtoList.stream().map(ImageDto::getUrl).collect(Collectors.joining(","));
                    wmNews.setType(3);
                    wmNews.setImages(imagesStr);
                }else{
                    //无图
                    wmNews.setType(0);
                    wmNews.setImages(null);
                }
                break;
        }
    }

    /**
     * 从文章正文中获取图片
     *
     * @param content [{type:"text",value:"文本"},{type:"image",value:"http://l92.168.137.136:9000/1.png"}]
     * @return
     */
    private List<ImageDto> getIamgeFromContent(String content) {
        //1.将内容转为JSON数组--List<ContentDto>
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        //2.遍历获取图片类型
        List<ImageDto> imageDtoList = new ArrayList<>();
        for (ContentDto contentDto : contentDtos) {
            if ("image".equals(contentDto.getType())) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }


    /**
     * 将文章跟素材建立关联
     *
     * @param imageDtoList 内容图片集合 或者 正文图片集合
     * @param type         0：内容引用  1：封面引用
     * @param newsId       文章ID
     */
    private void saveArticleMaterialRelation(List<ImageDto> imageDtoList, Integer type, Integer newsId) {
        int ord = 0;
        if (!CollectionUtils.isEmpty(imageDtoList)) {
            for (ImageDto imageDto : imageDtoList) {
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setMaterialId(imageDto.getId());
                wmNewsMaterial.setNewsId(newsId);
                wmNewsMaterial.setType(type);
                wmNewsMaterial.setOrd(ord++);
                newsMaterialService.save(wmNewsMaterial);
            }
        }
    }

    /**
     * 根据文章ID查询文章详情信息
     * @param id 文章ID
     * @return
     */
    @GetMapping("/{id}")
    public ResponseResult getById(@PathVariable("id") Integer id) {
        WmNews wmNews = wmNewsService.getById(id);
        return ResponseResult.okResult(wmNews);
    }
}

